package com.swift.authority.common.util;

import com.alibaba.fastjson.JSON;
import io.netty.util.internal.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 * @description :
 * @date 2022/06/18 22:55
 * @since open jdk 1.8
 */
@Component
public class RedisUtil {
    private Logger logger = LoggerFactory.getLogger(RedisUtil.class);

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 批量读取缓存
     *
     * @param keyList 入参
     * @return List
     */
    public Object batchGetValueList(final List<String> keyList) {
        try {
            if (keyList.isEmpty()) {
                logger.info("The input key cannot be empty ");
                return null;
            }

            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            Object value = operations.get(keyList);

            if (null != value) {
                logger.info("Reading cache succeeded , value:{}", JSON.toJSONString(value));
                return value;
            } else {
                logger.info("Reading cache Failed , value:{}", JSON.toJSONString(value));
                return null;
            }
        } catch (Exception e) {
            logger.info("Reading cache exception , {}", e.getMessage());
            return null;
        }
    }

    /**
     *  写入数据到缓存
     *
     * @param key 键
     * @param value 值
     * @return true 、 false
     */
    public boolean saveToCache(final String key, Object value) {
        boolean result = false;
        try {
            result = hasKey(key);
            if (result) {
                logger.info("The current key already exists,{}", result);
                return true;
            } else {
                ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
                operations.set(key, value);
                logger.info("The current key is saved successfully:{}", result);
            }
        } catch (Exception e) {
            logger.info("Save to cache exception, result:{}", result);
        }
        return result;
    }

    /**
     * 写入缓存设置时,并设置失效时间
     *
     * @param key 键
     * @param value 值
     * @return true / false
     */
    public boolean saveAndExpire(final String key, Object value, Long expireTime) {
        try {
            if (StringUtil.isNullOrEmpty(key)) {
                logger.info("The key can not be empty {}",key);
                return false;
            }
            if (null == value) {
                logger.info("The value can not be empty {}",value);
                return false;
            }
            if (null == expireTime) {
                logger.info("The expireTime can not be empty {}",expireTime);
                return false;
            }

            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            return redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
        } catch (Exception e) {
            logger.error("Set Value And Set Expire exception {}",e.getMessage());
            return false;
        }
    }

    /**
     * 批量删除key
     *
     * @param pattern 入参
     */
    public void batchDeleteKeys(final List<String> pattern) {
        try {
            if (pattern.isEmpty()) {
                logger.info("The key can not be empty ! {}", pattern.size());
            }

            Set<Serializable> keys = redisTemplate.keys(pattern);
            Long result = -1L;
            if (keys.size() > 0) {
                result = redisTemplate.delete(keys);
                logger.info("Deleting cache.....");
            }

            if (result == 0) {
                logger.info("Deleting cache succeeded  {}", result);
            }

        } catch (Exception e) {
            logger.info("Deleting cache exception  {}", e.getMessage());
        }
    }

    /**
     * @description 根据key 获取过期时间
     * @param key 键
     * @return 时间(秒) 返回0代表为永久有效
     */
    public long getExpire(String key) {
        if (StringUtil.isNullOrEmpty(key)) {
            logger.info("The key can not be empty {}", key);
            return -1;
        }
        try {
            return redisTemplate.getExpire(key, TimeUnit.SECONDS);
        }catch (Exception e){
            logger.error("get Expire exception {}",e.getMessage());
            return -2;
        }
    }

    /**
     * 判断key是否存在
     * @param key 键
     * @return true / false
     */
    public boolean hasKey(String key) {
        try {
            if (key.isEmpty()) {
                logger.info("The key can not be empty ! {}", key);
                return false;
            }
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            logger.error("Key query exception , {}", e.getMessage());
            return false;
        }
    }
}
